package leetcode.L2;

class ListNode {
  int val;
  ListNode next;
  ListNode() {}
  ListNode(int val) { this.val = val; }
  ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public class Solution {
    public ListNode addTwoNumbers(ListNode l1, ListNode l2) {
        //由于是逆序，所以这里可以直接相加，保留进位即可
        ListNode head=null;
        ListNode tail=head;

        int carry=0;
        //只要l1 l2一个不是null，就没结束
        while (l1!=null||l2!=null) {//两个一个为真即可循环
            int n1 = l1 == null ? 0 : l1.val;
            int n2 = l2 == null ? 0 : l2.val;
            //当前值:
            int currVal = (n1 + n2 + carry) % 10;
            carry = (n1 + n2 + carry) / 10;//超过10的部分作为进位
            if (head == null) {//首次创建
                head = new ListNode(currVal);
                tail = head;
            } else {
                tail.next=new ListNode(currVal);
                tail = tail.next;
            }
            if (l1 != null) {
                l1 = l1.next;
            }
            if (l2 != null) {
                l2 = l2.next;
            }
        }
        if (carry>0){
            tail.next=new ListNode(carry);
            tail = tail.next;
        }
        return head;
    }
}